<template>
  <div>
    <div ref="chart" id="main" style="width: 70%; height: 700px"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { getToken } from "@/utils/auth";
// import { WAREHOUSES_PATH } from "../../../api/constants/constants.js";

export default {
  name: "BasicStatsChart",
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const token = getToken();
        // const encodedFilePath = WAREHOUSES_PATH;
        // const decodedFilePath = decodeURIComponent(encodedFilePath);
        const response = await axios.get(`${process.env.VUE_APP_BASE_API}/wareHouses/mtbf`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        // console.log("Received data22:", response.data);

        if (typeof response.data === "string") {
          try {
            // 从字符串中提取 JSON 数据
            const jsonStartIndex = response.data.indexOf("{");
            const jsonEndIndex = response.data.lastIndexOf("}");
            if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
              const jsonData = response.data.substring(
                jsonStartIndex,
                jsonEndIndex + 1
              );
              const parsedData = JSON.parse(jsonData);
              // console.log("Parsed data:", parsedData);
              this.renderChart(parsedData);
            } else {
              console.error("No valid JSON found in response data");
            }
          } catch (parseError) {
            console.error("Error parsing JSON:", parseError);
          }
        } else if (typeof response.data === "object") {
          // console.log("Data is already an object:", response.data);
          this.renderChart(response.data);
        } else {
          // console.error("Unexpected data type:", typeof response.data);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
    renderChart(data) {
      // console.log("Data to render:", data);

      // 检查 data 是否为空
      if (!data || Object.keys(data).length === 0) {
        console.error("Data is empty or undefined");
        return;
      }

      const frequencies = Object.values(data).map((item) => item.frequency);
      const averageCompletionTimes = Object.values(data).map(
        (item) => item.AverageCompletionTime
      );

      // console.log("Frequencies:", frequencies);
      // console.log("Average Completion Times:", averageCompletionTimes);

      const chartDom = document.getElementById("main");
      const myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        legend: {
          data: ["故障次数", "平均完成时长"],
        },
        xAxis: [
          {
            type: "category",
            data: Object.keys(data).map((key) => key),
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "故障次数",
            min: 0,
            max: Math.max(...frequencies) + 10, // 动态设置最大值
            interval: 10,
            axisLabel: {
              formatter: "{value}",
            },
          },
          {
            type: "value",
            name: "平均完成时长",
            min: 0,
            max: Math.max(...averageCompletionTimes) + 10, // 动态设置最大值
            interval: 10,
            axisLabel: {
              formatter: "{value} 分钟",
            },
          },
        ],
        series: [
          {
            name: "故障次数",
            type: "bar",
            data: frequencies,
            yAxisIndex: 0,
          },
          {
            name: "平均完成时长",
            type: "line",
            data: averageCompletionTimes,
            yAxisIndex: 1,
          },
        ],
      };

      myChart.setOption(option);
    },
  },
};
</script>

<style scoped>
#main {
  margin: 20px;
}
</style>
